package de.pharmacontrol.jdni;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class JdniRepository {

	public static final String JDBC_DATASOURCE_CONTEXT = "jdbc/__default";
	public static final String JCO_SERVER_CONTEXT = "sap/ServerData";
	public static final String JCO_DESTINATION_CONTEXT = "sap/DestinationData";

	public static JdniRepository instance = new JdniRepository();

	private JdniRepository() {
	}

	public static JdniRepository getInstance() {
		return instance;
	}

	public Connection getJdbcConnection() {

		Connection result = null;
		try {

			Context initialContext = new InitialContext();
			DataSource datasource = (DataSource) initialContext.lookup(JDBC_DATASOURCE_CONTEXT);
			if (datasource != null) {
				result = datasource.getConnection();
			} else {
				Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Failed to lookup jdbc datasource.");
			}
		} catch (NamingException ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Connection error: " + ex.getMessage());
		} catch (SQLException ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Connection error: " + ex.getMessage());
		}
		return result;
	}

	public Properties getDestinationProperties() {

		Properties result = null;
		try {

			Context initialContext = new InitialContext();
			result = (Properties) initialContext.lookup(JCO_DESTINATION_CONTEXT);
		} catch (NamingException ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Properties error: " + ex.getMessage());
		} catch (Exception ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Properties error: " + ex.getMessage());
		}
		return result;
	}

	public Properties getServerProperties() {

		Properties result = null;
		try {

			Context initialContext = new InitialContext();
			result = (Properties) initialContext.lookup(JCO_SERVER_CONTEXT);

		} catch (NamingException ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Properties error: " + ex.getMessage());
		} catch (Exception ex) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).warning("Properties error: " + ex.getMessage());
		}
		return result;
	}

}
